//
//  FirstCarOwnerViewController.m
//  UcarTest
//
//  Created by 陈曦 on 16/3/15.
//  Copyright © 2016年 chenxi. All rights reserved.
//

#import "FirstCarOwnerViewController.h"
#import "Define.h"
#import "CarOwnerOrdersTableViewCell.h"
#import "AFNetworking.h"
#import "NetRequestGroup.h"
#import "Access_token.h"
#import "MBProgressHUD.h"
#import "CarOwnerOrdersModel.h"

@interface FirstCarOwnerViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, strong) UITableView *allRenterOrdersTV;

@property (nonatomic, strong) CarOwnerOrdersTableViewCell *cell;

@property (nonatomic, strong) NSMutableArray *listArray;

@end

@implementation FirstCarOwnerViewController

static NSString *reidentifierAll = @"cell";

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //背景色
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self setUpTableView];
    
    //网络请求
    self.nowPage = 0;
    [self NetworkRequests];
    
    
}

#pragma mark 网络请求
- (void) NetworkRequests{
    
    self.listArray = [NSMutableArray array];
    
    //初始化进度框，置于当前的View当中
    MBProgressHUD *HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:HUD];
    HUD.label.text = @"正在加载";
    [HUD showAnimated:YES];//HUD开始
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    //申明返回的结果是json类型
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    //申明请求的数据是json类型
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    //如果报接受类型不一致请替换一致text/html或别的
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    
    Access_token *useAccess = [Access_token shareInstance];
    
    
    NSString *nPage = [NSString stringWithFormat:@"%ld", self.nowPage];
    //传入的参数
    NSDictionary *para = @{
                           @"type" : @"1",
                           @"access_token" : useAccess.access_token,
                           @"page" : nPage,
                           @"app_order_status" : @"0"
                           };
    //你的接口地址
    NSString *url = [NSString stringWithFormat:@"%@%@", kRealmName,kNetCarOrderList];
    //发送请求
    [manager POST:url parameters:para success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        [HUD hideAnimated:YES];
        
        
        NSDictionary *dic = responseObject;
        
        
        NSDictionary *info = dic[@"info"];
        
        NSString *page_count = info[@"page_count"];
        
        
        NSDictionary *listDic = dic[@"info"];
        
        for (NSDictionary *diccc in listDic[@"list"]) {
            
            CarOwnerOrdersModel  *carListModel = [[CarOwnerOrdersModel alloc] init];
            [carListModel setValuesForKeysWithDictionary:diccc];
            
            [self.listArray addObject:carListModel];
            
            
        }
        
        
        [self.allRenterOrdersTV reloadData];
        
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        [HUD hideAnimated:YES];
        
        //初始化提示框；
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"没有网络" preferredStyle:  UIAlertControllerStyleAlert];
        
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //点击按钮的响应事件；
        }]];
        
        //弹出提示框；
        [self presentViewController:alert animated:true completion:nil];
        
        
    }];
    
}


//创建tableView
- (void) setUpTableView {
    
    self.allRenterOrdersTV = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 110)];
    self.allRenterOrdersTV.delegate = self;
    self.allRenterOrdersTV.dataSource = self;
    self.allRenterOrdersTV.separatorStyle = UITableViewCellSeparatorStyleNone;//去掉分割线
    [self.view addSubview:self.allRenterOrdersTV];
    
    [self.allRenterOrdersTV registerClass:[CarOwnerOrdersTableViewCell class] forCellReuseIdentifier:reidentifierAll];
    
    [self headerWithRefreshing];
    
    [self footerWithRefreshing];
    
}

//========================主页UItableViewDamo===================================
#pragma mark 主页UItableViewDamo
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.listArray.count;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 210;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    self.cell = [tableView dequeueReusableCellWithIdentifier:reidentifierAll forIndexPath:indexPath];
    self.cell.model = self.listArray[indexPath.row];
    
    [self.cell.rejectBtn  addTarget:self action:@selector(goToPayBlockBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.cell.sureBtn addTarget:self action:@selector(defineBlockBtn:) forControlEvents:UIControlEventTouchUpInside];
    
    NSInteger tagID = [self.cell.model.id intValue];
    
    [self.cell.sureBtn setTag:tagID];
    
    [self.cell.rejectBtn setTag:tagID];

    return self.cell;
    
}

- (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];//关闭选中状态

    self.cell.model = self.listArray[indexPath.row];

    _pushBlock(self.cell.model.id,self.cell.model.order_status);

}

//=============================此处以上===========================================


#pragma mark 下拉刷新
- (void)headerWithRefreshing{
    
    
    self.allRenterOrdersTV.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        if(self.nowPage > 0) {
            
            //当页数大于0 上拉刷新为 -1
            self.nowPage = self.nowPage - 1;
            
            // 模拟延迟加载数据，因此2秒后才调用（真实开发中，可以移除这段gcd代码）
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                //网络解析
                [self NetworkRequests];
                
                //刷新数据
                [self.allRenterOrdersTV reloadData];
                
                //删除当前页
                [self.allRenterOrdersTV removeFromSuperview];
                
                // 结束刷新
                [self.allRenterOrdersTV.mj_header endRefreshing];
                
                //重新载入列表
                [self setUpTableView];
                
            });
        } else if (self.nowPage <= 0) {
            
            // 模拟延迟加载数据，因此2秒后才调用（真实开发中，可以移除这段gcd代码）
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                //网络解析
                [self NetworkRequests];
                
                //刷新数据
                [self.allRenterOrdersTV reloadData];
                
                //删除当前页
                [self.allRenterOrdersTV removeFromSuperview];
                
                // 结束刷新
                [self.allRenterOrdersTV.mj_header endRefreshing];
                
                //重新载入列表
                [self setUpTableView];
                
            });
            
        }
        
    }];
}

#pragma mark 上拉刷新
- (void) footerWithRefreshing{
    
    
    // 上拉刷新
    self.allRenterOrdersTV.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        
        if (self.nowPage < self.allPage - 1) {
            
            //上拉为当前页数加1
            self.nowPage = self.nowPage + 1;
            
            // 模拟延迟加载数据，因此2秒后才调用（真实开发中，可以移除这段gcd代码）
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                //网络解析
                [self NetworkRequests];
                
                //刷新数据
                [self.allRenterOrdersTV reloadData];
                
                //删除当前页
                [self.allRenterOrdersTV removeFromSuperview];
                
                // 结束刷新
                [self.allRenterOrdersTV.mj_header endRefreshing];
                
                //重新载入列表
                [self setUpTableView];
                
            });
            
        } else if (self.nowPage >= self.allPage - 1){
            
            // 模拟延迟加载数据，因此2秒后才调用（真实开发中，可以移除这段gcd代码）
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                //网络解析
                [self NetworkRequests];
                
                //刷新数据
                [self.allRenterOrdersTV reloadData];
                
                //删除当前页
                [self.allRenterOrdersTV removeFromSuperview];
                
                // 结束刷新
                [self.allRenterOrdersTV.mj_header endRefreshing];
                
                //重新载入列表
                [self setUpTableView];
                
                
            });
            
            
        }
        
    }];
    
}

#pragma mark 跳转到拒绝界面

- (void) goToPayBlockBtn:(id)sender {
    
    NSInteger tagID = [sender tag];
    
    NSString *orderID = [NSString stringWithFormat:@"%ld", tagID];
    
    _refuseBlock(orderID);
    
}

#pragma mark 跳转到支付押金界面

- (void) defineBlockBtn:(id)sender {
    
    NSInteger tagID = [sender tag];
    
    NSString *orderID = [NSString stringWithFormat:@"%ld", tagID];
    
    _defineBlock(orderID);
    
}

@end
